package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.*;
import com.itheima.entity.YddArticle;
import com.itheima.entity.YddCate;
import com.itheima.entity.YddUser;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.dto.BaseInfoDto;
import com.itheima.dto.ProfileDto;
import com.itheima.entity.SysUser;
import com.itheima.service.IndexService;
import com.itheima.service.SysUserService;
import com.itheima.untils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private IndexService indexService;

    @Autowired
    private YddArticleService yddArticleService;

    @Autowired
    private YddCateService yddCateService;

    @Autowired
    private YddUserService yddUserService;

    /**
     * 登录
     * @param sysUser
     * @return
     */
    @PostMapping("/login")
    public R<Map<String, String>> login(@RequestBody SysUser sysUser) {
        //将页面提交的密码password进行md5加密处理
        String password = sysUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getLoginName, sysUser.getLoginName());
        SysUser user = sysUserService.getOne(queryWrapper);
        //如果没有查询到则返回登录失败结果
        if (user == null) {
            return R.error("登录失败");
        }
        //密码比对，如果不一致则返回登录失败结果
        if (!user.getPassword().equals(password)) {
            return R.error("登录失败");
        }
        //查看管理员状态，如果为已禁用状态，则返回员工已禁用结果
        if (user.getStatus() == 0) {
            return R.error("账号已禁用");
        }
        //登录成功，生成Token返回
        Map<String, String> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("login_name", user.getLoginName());
        String token = JwtUtils.generateToken(map);
        log.info("生成的token值为：{}", token);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return R.success(tokenMap);
    }

    /**
     * 注册
     * @param yddUser
     * @return
     */
    @PostMapping("/reg")
    public R<HashMap> reg(@RequestBody YddUser yddUser) {

        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(yddUser.getMobile() != null, YddUser::getMobile, yddUser.getMobile());
        YddUser one = yddUserService.getOne(queryWrapper);
        if (one == null) {
            YddUser user = new YddUser();
            user.setUsername(yddUser.getMobile());
            user.setMobile(yddUser.getMobile());
            String password = DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes());
            user.setPassword(password);
            user.setSex(1);
            yddUserService.save(user);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", user.getId());
            hashMap.put("username", user.getUsername());

            String token = JwtUtils.generateToken(hashMap);

            HashMap<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            return R.success(tokenMap);

        }


        return R.error("改手机号已注册");
    }
    /**
     * 获取系统配置
     *
     * @return
     */
    @GetMapping("/getConfig")
    public R<Map<String, String>> getConfig() {
        Map<String, String> sysConfigMap = indexService.getConfig();
        return R.success(sysConfigMap);
    }

    /**
     * 获取用户资料
     *
     * @param request
     * @return
     */
    @PostMapping("/profile")
    public R<ProfileDto> profile(HttpServletRequest request) {
        //获取请求头的token
        String token = request.getHeader("x-token");
        Claims claims = JwtUtils.parseToken(token);
        //获取登录的id
        String id = (String) claims.get("id");
        log.info("登录的用户的id:{}", id);

        ProfileDto profileDto = indexService.getProfile(id);
        return R.success(profileDto);
    }

    /**
     * 主页统计信息
     *
     * @return
     */
    @GetMapping("/baseInfo")
    @Cacheable(value = "indexCache" ,key = "'baseInfo'", unless = "#result.data==null")
    public R<BaseInfoDto> baseInfo(){
        BaseInfoDto baseInfoDto = indexService.getBaseInfo();
        return R.success(baseInfoDto);
    }


    /**
     * 前台最新文章
     *
     * @return
     */
    @GetMapping("/hot")
    public R<FrontHotDto> hot() {
        FrontHotDto frontHotDto = new FrontHotDto();

        Page<YddArticle> page = new Page<>(1, 8);

        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getIshot, 1);

        Page<YddArticle> page1 = yddArticleService.page(page, queryWrapper);
        List<YddArticle> list = page1.getRecords();

        List<ArticleDto> list1 = list.stream().map(item -> {
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(item, articleDto);

            Integer cateid = item.getCateid();
            YddCate cate = yddCateService.getById(cateid);
            if (cate != null) {
                String catename = cate.getCatename();
                articleDto.setCatename(catename);
            }

            return articleDto;
        }).collect(Collectors.toList());

        frontHotDto.setDesc("侧边最新文章");
        frontHotDto.setList(list1);

        return R.success(frontHotDto);
    }


    /**
     * 前台推荐文章
     * @return
     */
    @GetMapping("/recommend")
    public R<FrontHotDto> recommend() {
        FrontHotDto frontHotDto = new FrontHotDto();

        Page<YddArticle> page = new Page<>(1, 8);

        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getIstop, 1);

        Page<YddArticle> page1 = yddArticleService.page(page, queryWrapper);
        List<YddArticle> list = page1.getRecords();

        List<ArticleDto> list1 = list.stream().map(item -> {
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(item, articleDto);

            Integer cateid = item.getCateid();
            YddCate cate = yddCateService.getById(cateid);
            if (cate != null) {
                String catename = cate.getCatename();
                articleDto.setCatename(catename);
            }

            return articleDto;
        }).collect(Collectors.toList());

        frontHotDto.setDesc("侧边最新文章");
        frontHotDto.setList(list1);

        return R.success(frontHotDto);
    }

    /**
     * 前台热门置顶文章数据(首页）
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/new")
    public R<ArticlePageDto> indexNew(String page, String limit) {
        ArticlePageDto articlePageDto = yddArticleService.indexnew(page, limit);

        long nowTime = System.currentTimeMillis();
        long time = nowTime - (24 * 3600 * 1000);
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(YddArticle::getCreateDate, time);
        int count = yddArticleService.count(queryWrapper);

        long timeWeek = nowTime - (24 * 3600 * 1000 * 7);
        LambdaQueryWrapper<YddArticle> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.gt(YddArticle::getCreateDate, timeWeek);
        int count1 = yddArticleService.count(queryWrapper1);


        articlePageDto.setNum_day(count);
        articlePageDto.setNum_week(count1);
        return R.success(articlePageDto);
    }
    /**
     * 前台首页和全局数据
     *
     * @return
     */
    @GetMapping("/index")
    public R<FrontIndexDto> index() {
        FrontIndexDto frontIndexDto = indexService.index();
        return R.success(frontIndexDto);
    }

    /**
     * 前台文章列表数据
     *
     * @param page
     * @param limit
     * @param cateid
     * @return
     */
    @GetMapping("/list")
    public R<HashMap<String, Object>> indexList(String page, String limit, String cateid) {

        PageDto list = indexService.getList(page, limit, cateid);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list", list);
        return R.success(hashMap);

    }

    /**
     * 展示文章的详细信息
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/show")
    public R<HashMap> show(Integer id, HttpServletRequest request) {

        HashMap<String, Object> hashMap = indexService.getShow(id, request);
        return R.success(hashMap);
    }
}